package com.app.micaihu.manager;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;

import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.receiver.DemoIntentService;
import com.app.micaihu.receiver.DemoPushService;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.view.main.DispatchActivity;
import com.app.utils.util.AppTools;
import com.app.utils.util.StringUtils;
import com.baidu.mobstat.MtjConfig;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Guo on 2016/8/8.
 * <p>
 * 推送的管理类
 */
public class IPushManager implements DialogUtils.OnDialogBtnClickListener {

    private static IPushManager iPushManager;
    private NewsEntity newsEntity;//当前推送的实体类信息
    private Activity activity;
    private String pushType;


    private IPushManager() {
    }


    public static IPushManager getInstance() {
        if (iPushManager == null) {
            iPushManager = new IPushManager();
        }
        return iPushManager;
    }

    /**
     * 初始化小米推送
     */
    public void initMiPush() {
        //if(shouldInit()){
        MiPushClient.registerPush(AppApplication.getInstance(), AppConfigTools.MIPUSH_APPID, AppConfigTools.MIPUSH_APPKEY);
        //}
        //设置topic
        MiPushClient.subscribe(AppApplication.getInstance(), AppTools.getVersionName(), null);
    }

    /**
     * 初始化友盟推送
     */
    public void initUmengPush() {
        PushManager.getInstance().initialize(AppApplication.getInstance(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(AppApplication.getInstance(), DemoIntentService.class);
        //开启友盟的自定义消息推送
//        UmengPushMessageReceiver umengPushMessageReceiver = new UmengPushMessageReceiver();
//
//        final PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
//        final String versionName = AppTools.getVersionName();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    mPushAgent.getTagManager().add(versionName);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }).start();
//
//        //开启/关闭友盟的调试模式
//        mPushAgent.setDebugMode(BuildConfig.LOG_DEBUG);
//
//        mPushAgent.setMessageHandler(umengPushMessageReceiver);
//        mPushAgent.enable(iUmengRegisterCallback);

    }


    /**
     * 如果是小米手机,就只注册小米的推送
     * 如果是非小米手机,注友盟
     */
    public void initDoublePushByBuildMode() {
        if (AppConfigManager.getInstance().readConfig(ConfigKeyConstant.option_isPull, true)) {
            String manufacturer = Build.MANUFACTURER;
            if (!TextUtils.isEmpty(manufacturer) && TextUtils.equals(manufacturer, "Xiaomi")) {
                initMiPush();
            } else {
                initUmengPush();
            }
        }


    }


    /**
     * 停止推送
     * 根据机型停止对应的推送
     */
    public void endPush() {
        String manufacturer = Build.MANUFACTURER;
        if (!TextUtils.isEmpty(manufacturer) && TextUtils.equals(manufacturer, "Xiaomi")) {
            //关闭小米推送
            MiPushClient.unregisterPush(AppApplication.getInstance());
        } else {
            //关闭友盟推送
//            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
//            mPushAgent.disable(iUmengUnregisterCallback);
        }

        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_dialog_show_time, 0L);

    }


    /**
     * 开启推送
     * 根据机型开启对应的push
     */
    public void startPush() {
        String manufacturer = Build.MANUFACTURER;
        if (!TextUtils.isEmpty(manufacturer) && TextUtils.equals(manufacturer, "Xiaomi")) {
            //开启小米的自定义消息推送
            MiPushClient.registerPush(AppApplication.getInstance(), AppConfigTools.MIPUSH_APPID, AppConfigTools.MIPUSH_APPKEY);
        } else {
//            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
//            mPushAgent.enable(iUmengRegisterCallback);
        }
        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.option_isPull, true);
    }

//    /**
//     * 友盟注销的回调监听
//     */
//    public IUmengUnregisterCallback iUmengUnregisterCallback = new IUmengUnregisterCallback() {
//        @Override
//        public void onUnregistered(String s) {
//            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
//            boolean enabled = mPushAgent.isEnabled();
//        }
//    };
//
//    /**
//     * 友盟注册的回调
//     */
//    public IUmengRegisterCallback iUmengRegisterCallback = new IUmengRegisterCallback() {
//        @Override
//        public void onRegistered(String s) {
//            Log.e("umeng", "deviceToken--->" + s);
//            AppConfigManager.getInstance().writeConfig(UserConfigTools.UMENG_TOKEN, s);
////            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
////            boolean enabled = mPushAgent.isEnabled();
//
//        }
//    };


    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) AppApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = AppApplication.getInstance().getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 通知栏弹窗
     */
    public void showNotification(Context context, NewsEntity newsEntity, String pushType) {

        if (newsEntity == null) return;
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder;
        //判断是否是8.0Android.O
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan1 = new NotificationChannel("static", "Primary Channel", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(chan1);
            builder = new NotificationCompat.Builder(context, "static");
        } else {
            builder = new NotificationCompat.Builder(context);
        }
        String articleType = newsEntity.getArticleType();
        String articleId = newsEntity.getArticleId();
        String articleTitle = newsEntity.getArticleTitle();
        String articleSummary = newsEntity.getArticleSummary();
        builder.setContentTitle(articleTitle);
        builder.setContentText(articleSummary);
        //大于等于23系统,则使用黑白的icon,否则,使用彩色的icon,不过现在图标还没有设计好.所以先用彩色的
//        LogUtils.e("gzq", "sdkInt = "+sdkInt);
        builder.setSmallIcon(R.drawable.push_small);
        //大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(AppApplication.getInstance().getResources(), R.mipmap.icon));
        builder.setDefaults(Notification.DEFAULT_ALL);
//        builder.setColor(Color.parseColor("#000000"));//设置icon 的背景颜色
        builder.setAutoCancel(true);

        //设置intent.如果有url,则直接跳转url
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        LogUtils.e("gzq", "articleId = "+articleId+"\narticleType = "+articleType+"\njumpUrl = "+newsEntity.getJumpUrl());

        intent.putExtra(Config.Extra.PARAMETER1, articleId);
        intent.putExtra(Config.Extra.PARAMETER2, articleType);
        intent.putExtra(TypeConstant.PUSH_TYPE, pushType);
        if (!TextUtils.isEmpty(newsEntity.getJumpUrl())) {
            intent.putExtra("url", newsEntity.getJumpUrl());
        }
        if (!TextUtils.isEmpty(newsEntity.getSerialId())) {
            intent.putExtra("serialId", newsEntity.getSerialId());
        }
        intent.putExtra(DispatchActivity.PUSH_OR_WAKEUP, true);
        intent.setClass(context, DispatchActivity.class);
        // 百度统计 启动来源推送 来源统计
        intent.putExtra(MtjConfig.BAIDU_MTJ_PUSH_CALL, true);
        // 建议添加，如果是敏感信息，可以不添加，则报表上也就无法展现
        intent.putExtra(MtjConfig.BAIDU_MTJ_PUSH_MSG, newsEntity.getArticleTitle());
        int id = (int) (System.currentTimeMillis() / 1000);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        long articleIdLong = StringUtils.toLong(articleId, 0);
        int articleIdInt = Long.valueOf(articleIdLong).intValue();

        Notification notification = builder.build();
        manager.notify(articleIdInt, notification);

    }

    /**
     * 设置推送渠道号
     *
     * @param pushChannel
     */
    public void setPushChannel(String pushChannel) {
        if (!TextUtils.isEmpty(pushChannel)) {
//            PushAgent.getInstance(AppApplication.getInstance()).setMessageChannel(pushChannel);
        }
    }


    /**
     * 判断 当前应用是否在前台运行
     *
     * @param context
     * @return
     */
    public boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * 要闻推送的弹窗
     *
     * @param activity
     * @param newsEntity 此参数为空的时候，读取本地数据，否则，立即弹出dialog
     * @param pushType   推送类型
     */
    public void showFoucsDialog(Activity activity, NewsEntity newsEntity, String pushType) {
        if (!AppConfigTools.isShowPushDialog) {
            return;
        }
        this.activity = activity;
        this.pushType = pushType;
        AppConfigTools.isShowPushDialog = false;
        if (newsEntity != null) {//如果有文章id，直接弹出dialog
            this.newsEntity = newsEntity;
            showPushDialog(activity);
        } else {//否则，去除本地数据，比较过后再弹
            String pushData = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.push_foucusnews, "");
            if (!TextUtils.isEmpty(pushData)) {
                String[] pushStr = pushData.split("\\}_");
                if (pushStr.length >= 3) {
                    String pushContent = pushStr[0];
                    String pushTime = pushStr[1];
                    this.pushType = pushStr[2];
                    Long pushMills = Long.valueOf(pushTime);
                    long l = System.currentTimeMillis();
                    String pushExpireTimeStr = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.push_expireTime, "7200");
                    long pushExpireTimeLong = StringUtils.toLong(pushExpireTimeStr, 7200L);

                    if ((l - pushMills) > (pushExpireTimeLong * 1000)) {//当前时间超过两小时，重置
                        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_foucusnews, "");
                    } else {
                        //解析content
                        Gson gson = new Gson();
                        try {
                            this.newsEntity = gson.fromJson(pushContent, NewsEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            gson = null;
                        }
                        showPushDialog(activity);
                    }
                }
            }
        }
    }


    private void showPushDialog(Activity activity) {
        HashMap<String, String> style = new HashMap<>();
        style.put("title", activity.getString(R.string.push_dialog_title));
        style.put("desc", this.newsEntity.getArticleTitle());
        style.put("btnPosi", activity.getString(R.string.push_go));
        style.put("btnNega", activity.getString(R.string.push_ignore));

        DialogUtils.getInstance().setOnDialogBtnClick(this);
        DialogUtils.getInstance().showCustomDialog(activity, style);

        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_foucusnews, "");
    }


    @Override
    public void onPositiveClick() {
        DialogUtils.getInstance().dismissCustomDialog();
        StatService.onEvent(AppApplication.getInstance(), "028", "要闻推送点击", 1);// 统计的点击的次数

        TypeConstant.openTypeDetail(newsEntity, activity, TypeConstant.SOURCETYPE_PUSH);//跳转新闻详情

    }

    @Override
    public void onNegativeClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }
}
